package com.TeacherInfoServer.listener;

import com.TeacherInfoServer.exception.RecordExistDetailException;
import com.TeacherInfoServer.exception.TeacherNameNotExistException;
import com.TeacherInfoServer.pojo.entity.Department;
import com.TeacherInfoServer.pojo.excelImport.DepartmentExcel;
import com.TeacherInfoServer.common.service.CommentService;
import com.TeacherInfoServer.common.service.DepartmentService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Data
@Component
public class DepartmentListener implements ReadListener<DepartmentExcel> {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CommentService commentService ;
    @Autowired
    private Validator validator;
    private final List<Department> departmentList = new ArrayList<>();
    private final List<Department> updateList = new ArrayList<>();
    private final List<Department> addList = new ArrayList<>();
    private final Set<String> departmentNameSet = new HashSet<>();
    private Integer record;

    @Override
    public void invoke(DepartmentExcel departmentExcel, AnalysisContext analysisContext) {
        Set<ConstraintViolation<DepartmentExcel>> violations = validator.validate((departmentExcel));
        if (violations.isEmpty()){
                if((commentService.findTeacherByName(departmentExcel.getLeaderName())!=null)&&(commentService.findTeacherByName(departmentExcel.getDirectorName())!=null)){
                    if(!departmentNameSet.contains(departmentExcel.getName())){
                        Department department =new Department(null,
                                departmentExcel.getName(),
                                commentService.findTeacherByName(departmentExcel.getLeaderName()).getTeacherId(),
                                commentService.findTeacherByName(departmentExcel.getDirectorName()).getTeacherId());
                        departmentList.add(department);
                        departmentNameSet.add(departmentExcel.getName());
                    }else {
                        throw new RecordExistDetailException("表中存在相同教研室名称："+departmentExcel.getName());
                    }
                }else {
                    throw new TeacherNameNotExistException("教研室名称为："+departmentExcel.getName()+"的教研室中的"+departmentExcel.getLeaderName()+"或"+departmentExcel.getDirectorName()+"教师名称不存在");
                }

        }else {
            String errorMessage = violations.iterator().next().getMessage();
            throw new ConstraintViolationException(errorMessage, violations);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
     List<Department> departments = departmentService.list();
     departmentList.forEach(department -> {
         Optional<Department> departmentOptional = departments.stream()
                 .filter(dbDepartment-> department.getName().equals(dbDepartment.getName()))
                 .findFirst();
         departmentOptional.ifPresent(dbDepartment -> {
             department.setId(dbDepartment.getId());
             updateList.add(department);
         });
         if(departmentOptional.isEmpty()){
             addList.add(department);

         }

     });
     List<Department> mergedList = Stream.concat(updateList.stream(),addList.stream()).collect(Collectors.toList());
     departmentService.saveOrUpdateBatch(mergedList);
     setRecord(mergedList.size());
     initList();
    }

    public void initList(){
        departmentList.clear();
        updateList.clear();
        addList.clear();
        departmentNameSet.clear();
    }
}
